package main

import (
	. "config"
	"fmt"
	"github.com/robfig/cron/v3"
	"myerror"
	"os"
	"time"
)

// CreateLogFile 创建日志件并设置为默认日志文件的函数，由DoSthOnTime()在午夜十二点定时调用
func CreateLogFile() {
	var err error
	T = time.Now()
	fn := fmt.Sprint("./log/", T.Year(), "-", T.Month(), "-", T.Day(), " ", T.Hour(), "-", T.Minute(), "-", T.Second(), " chat.log")
	go fmt.Printf("create log file:%s", fn)
	stdout, err := os.Create(fmt.Sprint("./log/", T.Year(), ";", T.Month(), ";", T.Day(), " ", T.Hour(), ";", T.Minute(), ";", T.Second(), "stdout chat.log"))
	if err != nil {
		fmt.Println("文件创建错误：", err.Error())
		return
	}
	os.Stdout = stdout
	stderr, err := os.Create(fmt.Sprint("./log/", T.Year(), ";", T.Month(), ";", T.Day(), " ", T.Hour(), ";", T.Minute(), ";", T.Second(), "stderr chat.log"))
	if err != nil {
		fmt.Println("文件创建错误：", err.Error())
		return
	}
	os.Stderr = stderr
}

// DoSthOnTime 用于定时任务
func DoSthOnTime() {
	c := cron.New()
	_, err := c.AddFunc("0 0 * * *", CreateLogFile)
	if err != nil {
		myerror.LogWarning(err)
		return
	}
	c.Start()
}
